package com.example.quizamination.ui.main

import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.OnBackPressedCallback
import androidx.navigation.fragment.findNavController
import com.example.quizamination.R
import com.example.quizamination.databinding.FragmentResultBinding

private const val ARG_RESULT_TEXT = "resultText";

class ResultFragment : Fragment() {
    private var resultText: String? = null
    private var _binding: FragmentResultBinding? = null
    private val binding: FragmentResultBinding
        get() = _binding!!

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            resultText = it.getString(ARG_RESULT_TEXT)
        }
        val onBackPressedCallback = object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                findNavController().popBackStack(R.id.welcomeFragment, false)
            }
        }
        requireActivity().onBackPressedDispatcher.addCallback(this, onBackPressedCallback)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentResultBinding.inflate(inflater, container, false)
        binding.resTextView.text = resultText
        binding.repeatButton.setOnClickListener {
            findNavController().popBackStack(R.id.mainFragment, false)
        }
        val scaleX = ObjectAnimator.ofFloat(binding.resTextView, View.SCALE_X, 0f, 1f)
        val scaleY = ObjectAnimator.ofFloat(binding.resTextView, View.SCALE_Y, 0f, 1f)
        val rotation = ObjectAnimator.ofFloat(binding.repeatButton, View.ROTATION, 0f, 360f)

        scaleX.duration = 500
        scaleY.duration = 500
        rotation.duration = 500

        val animatorSet = AnimatorSet()
        animatorSet.playTogether(scaleX, scaleY, rotation)
        animatorSet.start()
        return binding.root
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    companion object {
        @JvmStatic
        fun newInstance(resultText: String) = ResultFragment().apply {
            arguments = Bundle().apply {
                putString(ARG_RESULT_TEXT, resultText)
            }
        }
    }
}